<template>
  <div class="box">
    <a-card>
      <a-row>
        <a-col :span="8">
          <a-form-item label="姓名" name="name" class="projectItem">
            <a-input v-model:value="parans.name" allowClear placeholder="请输入姓名"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="8"></a-col>
        <a-col :span="8" style="text-align:right">
          <a-space justify="end">
            <a-button @click="reset">重置</a-button>
            <a-button type="primary" @click="onSearch">查询</a-button>
          </a-space>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="4">
            <a-button type="primary" @click="showModal">新增用户</a-button>
        </a-col>
        <a-col :span="20"></a-col>
      </a-row>
    <div class="btn">

    </div>
    <a-table
      :pagination="pagination"
      :dataSource="dataSource"
      :columns="columns"
      :scroll="{ y: 540 }"
      @change="changepage"
    >
      <template #headerCell="{ title }">
        <div style="text-align: center">
          {{ title }}
        </div>
      </template>
      <template #bodyCell="{ column, record,index}">
        <template v-if="column.key == 'index'">
          {{ (pagination.current - 1) * pagination.pageSize + parseInt(index) + 1 }}
        </template>
        <template v-else-if="column.key == 'name'">
          <div class="avatar">
            <img v-if="record.avatar" :src="record.avatar" alt="" />
            <img v-else src="@/assets/images/defaultAvatar.svg" alt="" />
            <a>
              {{ record.name }}
            </a>
            <img v-if="record.isOwner" style="margin-left: 10px; width: 1.2em; height: 1.2em" src="@/assets/images/user-manage.svg"  />
          </div>
        </template>
        <template v-else-if="column.key == 'mobile'">
          <a>
            {{ record.mobile }}
          </a>
        </template>
        <template v-else-if="column.key == 'departments'">
          <a>
            {{ record.departments }}
          </a>
        </template>
        <template v-else-if="column.key == 'operate'">
          <a @click="details(record)" style="color: #2196f8" >详情</a>
          <a-divider type="vertical"/>
          <a-dropdown>
            <a style="color: #2196f8">操作<DownOutlined /></a>
            <template #overlay>
              <a-menu>
                <a-menu-item >
                  <a @click="edit(record)" style="color: #2196f8">编辑</a>
                </a-menu-item>
                <a-menu-item  v-if="Storage.Get(APP_USER).owner == MangeTypeEnum.SUPER_MANGE ">
                  <div v-if="record.isOwner">
                    <a-popconfirm
                      v-if="record.userId!==Storage.Get(APP_USER).userid"
                      title="你确定撤销该管理员吗?"
                      ok-text="确定"
                      cancel-text="取消"
                      @confirm="removeMange(record)"
                    >
                      <a style="color: #2196f8">撤销管理员</a>
                    </a-popconfirm>
                  </div>
                  <div v-else>
                    <a-popconfirm
                      title="你确定增加该管理员吗?"
                      ok-text="确定"
                      cancel-text="取消"
                      @confirm="setMange(record)"
                    >
                      <a style="color: #2196f8">设置管理员</a>
                    </a-popconfirm>
                  </div>
                </a-menu-item>
                <a-menu-item v-if="Storage.Get(APP_USER).userid !== record.userId">
                  <a-popconfirm
                    title="你确定要删除吗?"
                    ok-text="确定"
                    cancel-text="取消"
                    @confirm="confirm(record)"
                  >
                    <a style="color: #2196f8">删除</a>
                  </a-popconfirm>
                </a-menu-item>
              </a-menu>
            </template>
          </a-dropdown>
        </template>
      </template>
    </a-table>
    <div class="globalModal" ref="globalModal">
      <a-modal
        class="modal"
        :getContainer="() => $refs.globalModal"
        v-model:visible="visible"
        :title="title"
        @ok="handleOk"
        @cancel="cancel"
      >
        <div v-if="detailsList">
          <a-form
            :label-col="{ span: 4 }"
            :wrapper-col="{ span: 16 }"
            autocomplete="off"
            labelAlign="left"
          >
            <a-form-item
              style="
                display: flex;
                align-items: center;
                justify-content: center;
                text-align: center;
              "
            >
              <a-avatar style="margin: 0 auto" :size="80" :src="detailsInfo.avatar" />
            </a-form-item>

            <a-form-item label="姓名" name="name">
              {{ detailsInfo.name }}
            </a-form-item>

            <a-form-item label="账号" name="userId">
              {{ detailsInfo.userId }}
            </a-form-item>

            <a-form-item label="手机号">
              {{ detailsInfo.mobile }}
            </a-form-item>

            <a-form-item label="标签">
              <a-tag v-for="(item, index) in detailsInfo.tagList" :key="index">
                <tag-outlined />&nbsp;{{ item.name }}
              </a-tag>
            </a-form-item>
            <a-form-item label="部门">
              <a-tag v-for="(item, index) in detailsInfo.departList" :key="index">
                <team-outlined />&nbsp;{{ item.name }}
                <span style="background-color: #ccc; color: #fff" v-if="item.isLeader == 1"
                >负责</span
                >
              </a-tag>
            </a-form-item>
            <!--
            <a-form-item label="主部门" name="mainDepartId"> </a-form-item>

            <a-form-item label="部门负责人" name="mainDepartId"> </a-form-item> -->
          </a-form>
          <!-- <div style="display: flex; flex-direction: column">
            <a-avatar style="margin: 0 auto" :size="64" :src="detailsInfo.avatar" />
            <p
              >姓名：<span>{{ detailsInfo.name }}</span></p
            >
            <p
              >账号：<span>{{ detailsInfo.userId }}</span></p
            >
            <p
              >手机号：<span>{{ detailsInfo.mobile }}</span></p
            >
            <div
              >部门：
              <a-tag color="#87d068" v-for="(item, index) in detailsInfo.departList" :key="index">
                {{ item.name }}
              </a-tag></div
            >
            <div
              >标签：
              <a-tag color="cyan" v-for="(item, index) in detailsInfo.tagList" :key="index">
                {{ item.name }}
              </a-tag></div
            >
          </div> -->
        </div>
        <div v-else>
          <a-form
            :model="formState"
            name="basic"
            ref="formRef"
            :label-col="{ span: 4 }"
            :wrapper-col="{ span: 16 }"
            autocomplete="off"
            @finish="onFinish"
            @finishFailed="onFinishFailed"
          >
            <a-form-item
              style="
                display: flex;
                align-items: center;
                justify-content: center;
                text-align: center;
              "
            >
              <a-upload
                text= "请上传头像"
                name="avatar"
                list-type="picture-card"
                :max-count="1"
                class="avatar-uploader"
                :show-upload-list="false"
                :customRequest="uploadFile"
              >
                <img v-if="imageUrl" :src="imageUrl" alt="avatar" style="height: 100%" />
                <div v-else>
                  <plus-outlined></plus-outlined>
                  <div class="ant-upload-text">上传头像</div>
                </div>
              </a-upload>
            </a-form-item>

            <a-form-item
              label="姓名"
              name="name"
              :rules="[{ required: true, message: '请填写姓名' }]"
            >
              <a-input
                placeholder="请输入姓名"
                v-model:value="formState.name"
                @change="convertToPinyin"
              />
            </a-form-item>

            <a-form-item
              label="账号"
              name="userId"
              :rules="[{ required: true, message: '请填写账号' }]"
            >
              <a-input
                placeholder="请输入账号"
                :disabled="disabled"
                v-model:value="formState.userId"
              />
            </a-form-item>

            <a-form-item
              v-if="hide"
              label="密码"
              name="passwrod"
              :rules="[
                { required: true, message: '请输入密码' },
                {
                  pattern: /^(?=.*[a-z])(?=.*[0-9])(?=.*[^a-z0-9]).{8,16}$/i,
                  message: '密码由8 ~16位的字母、数字、特殊字符组成',
                },
              ]"
            >
              <a-input-password placeholder="请输入密码" v-model:value="formState.passwrod" />
            </a-form-item>

            <a-form-item
              label="手机号"
              name="mobile"
              :rules="[
                { required: true, message: '请输入手机号' },
                {
                  pattern: /^1(3|4|5|6|7|8|9)\d{9}$/,
                  message: '手机号不合法',
                },
              ]"
            >
              <a-input placeholder="请输入手机号" v-model:value="formState.mobile" />
            </a-form-item>

            <a-form-item label="标签" name="tagList">
              <!-- <a-select v-model:value="formState.tagList" :options="tagslist" @change="handleChange" /> -->
              <a-select
                v-model:value="value"
                mode="multiple"
                :show-search="true"
                optionFilterProp="label"
                placeholder="请选择标签"
                style="width: 200px"
                :options="tagslist"
                @change="changeTags"
              ></a-select>
              <!-- <a-checkbox-group
              name="checkboxgroup"
              v-model:value="value"
              :options="tagslist"
              @change="changeTags"
            /> -->
            </a-form-item>
            <a-form-item
              label="部门"
              name="departList"
              :rules="[{ required: true, message: '请选择部门' }]"
            >
              <a-tree-select
                v-model:value="formState.departList"
                style="width: 100%"
                :tree-data="departmentData"
                tree-checkable
                allow-clear
                tree-check-strictly
                placeholder="请选择部门"
                tree-node-filter-prop="label"
                @change="changeDepart"
              >
                <template #title="{ value: val, label }">
                  <div class="depart">{{ label }} </div>
                </template>
              </a-tree-select>
            </a-form-item>

            <a-form-item
              label="主部门"
              name="mainDepartId"
              :rules="[{ required: true, message: '选择主部门' }]"
            >
              <a-radio-group
                v-for="(item, index) in formState.departList"
                :key="index"
                v-model:value="formState.mainDepartId"
                name="radioGroup"
              >
                <a-radio :value="item.value">{{ item.label }}</a-radio>
                <!-- <a-radio value="2">B</a-radio>
              <a-radio value="3">C</a-radio>
              <a-radio value="4">D</a-radio> -->
              </a-radio-group>
            </a-form-item>

            <a-form-item label="部门负责人" name="mainDepartId">
              <a-checkbox-group
                @change="changeGroup"
                v-model:value="value1"
                name="checkboxgroup"
                :options="formState.departList"
              />
            </a-form-item>
          </a-form>
        </div>
      </a-modal>
    </div>
    </a-card>
  </div>
</template>

<script setup lang="ts">
  import {MangeTypeEnum} from "@/enums/mangeTypeEnum";

  defineOptions({
    name: 'userList',
  });
  import { ref, reactive } from 'vue';
  import { pinyin, customPinyin } from 'pinyin-pro';
  import {
    getMembers,
    delMembers,
    addMembers,
    getdepartment,
    getTag,
    getUserDetail,
    uploadAvatar, saveMange, deleteMange,
  } from '@/api/members/members';
  import {APP_USER} from '@/enums/cacheEnum';
  import { Storage } from '@/utils/Storage';
  import type { Record } from '@/api/members/members.d';
  import type { FormInstance } from 'ant-design-vue';
  import { message } from 'ant-design-vue';
  import { PlusOutlined, DownOutlined } from '@ant-design/icons-vue';
  // const SHOW_PARENT = TreeSelect.SHOW_PARENT;
  const dataSource = ref([] as Record[]);
  const parans = ref({
    pageNumber: 1,
    pageSize: 20,
    name: '',
    tenantId: Storage.Get(APP_USER).tenantid,
  });
  // 分页配置
  const pagination = reactive({
    current: 1,
    pageSize: 20,
    total: 50,
    showSizeChanger: true,
    showQuickJumper: true,
    pageSizeOptions: ['10', '20', '30', '40'],
    showTotal: (total: number) => `共 ${total} 条`,
  });
  // 获取所有人员
  const getMembersList = async () => {
    const res = await getMembers(parans.value);
    pagination.total = res.data.total;
    dataSource.value = res.data.records;
  };
  getMembersList();
  // 配置表头
  const columns = ref([
    {
      title: '序号',
      width: 60,
      key: 'index',
      align: 'center',
      fixed: 'left',
    },
    {
      title: '成员',
      dataIndex: 'name',
      key: 'name',
      align: 'center',
      width: 200,
      onFilter: (value: string, record: any) => record.name.indexOf(value) === 0,
      sorter: (a: any, b: any) => a.name.localeCompare(b.name), // 使用 localeCompare 进行字典顺序比较
      sortDirections: ['ascend', 'descend'], // 支持升序和降序
    },
    {
      title: '手机号',
      dataIndex: 'mobile',
      key: 'mobile',
      align: 'center',
    },
    {
      title: '部门',
      dataIndex: 'departments',
      key: 'departments',
      // align: 'left',
    },
    {
      title: '操作',
      width: 180,
      dataIndex: 'operate',
      key: 'operate',
      fixed: 'right',
      align: 'center',
    },
  ]);
  // 按姓名搜索人员
  // const search = ref<string>('');
  const onSearch = () => {
    parans.value.pageNumber = 1;
    parans.value.pageSize = 20;
    getMembersList();
  };
  // 重置
  const reset = () => {
    parans.value.name = '';
    parans.value.pageNumber = 1;
    pagination.current = 1;
    pagination.pageSize = 20;
    getMembersList();
  };
  // 表格翻页
  const changepage = e => {
    pagination.current = e.current;
    pagination.pageSize = e.pageSize;
    parans.value.pageNumber = e.current;
    parans.value.pageSize = e.pageSize;
    getMembersList();
  };
  // 删除用户
  const confirm = async (record: { userId: string }) => {
    console.log(record);
    const res = await delMembers({ userId: record.userId });
    message.success(res.msg);
    getMembersList();
  };
  // 获取所有部门
  const getDepartmentList = async () => {
    const res = await getdepartment({ tenantId: Storage.Get('power-user').tenantid });
    console.log(res);
    departmentData.value = convertData(res.data);
  };
  const convertData = data => {
    return data.map(item => ({
      value: item.id,
      label: item.name,
      children: item.children ? convertData(item.children) : [],
    }));
  };

  getDepartmentList();
  // 新增用户
  const disabled = ref(false);
  const hide = ref(true);
  const title = ref('新增人员');
  const visible = ref<boolean>(false);

  // 点击新增打开弹窗
  const showModal = () => {
    detailsList.value = false;
    hide.value = true;
    visible.value = true;
    disabled.value = false;
    title.value = '新增人员';
    // formState.name = '';
    // formState.userId = '';
    // formState.tagList = [];
    // formState.departList = [];
    // formState.mobile = '';
    // formState.passwrod = '';
    // formState.mainDepartId = '';
    // formState.avatar = '';
  };

  // 点击编辑回显的内容
  const edit = async record => {
    disabled.value = true;
    detailsList.value = false;
    hide.value = false;
    visible.value = true;
    title.value = '修改人员信息';
    const res = await getUserDetail({ userId: record.userId });

    formState.name = res.data.name;
    formState.userId = res.data.userId;
    formState.mobile = res.data.mobile;
    imageUrl.value = res.data.avatar;

    value.value = res.data.tagList.map(item => {
      return {
        value: item.tagId,
        label: item.name,
      };
    });
    formState.tagList = res.data.tagList;
    formState.departList = res.data.departList.map(item => {
      return {
        value: item.departId,
        label: item.name,
        isLeader: item.isLeader,
      };
    });
    formState.mainDepartId = res.data.mainDepartId;
    let list = res.data.departList.filter(item => item.isLeader == 1);
    // value1.value = [{ label: '他政报书', value: '4' }];
    value1.value = list.map(item => item.departId);
  };

  // 点击确定按钮触发的函数
  const handleOk = async () => {
    if (title.value == '查看人员详情') {
      visible.value = false;
    }
    formRef.value
      ?.validateFields()
      // ?.validate()
      .then(async values => {
        let departList = formState.departList.map(item => {
          return {
            value: item.value,
            isLeader: item.isLeader,
            departId: item.value,
            name: item.label,
          };
        });
        const res = await addMembers({
          userId: formState.userId,
          password: formState.passwrod,
          avatar: imageUrl.value,
          name: formState.name,
          mobile: formState.mobile,
          mainDepartId: formState.mainDepartId,
          tenantId: Storage.Get('power-user').tenantid,
          departList: departList,
          tagList: formState.tagList,
        });
        console.log(res);
        if (res.code == 0) {
          message.success(res.msg);
          visible.value = false;
          formRef.value?.resetFields();
          value.value = [];
          getMembersList();
        } else {
          message.success(res.msg);
          visible.value = false;
          formRef.value?.resetFields();
        }
      })
      .catch(info => {
        console.log('Validate Failed:', info);
      });
  };

  // 取消弹窗
  const cancel = () => {
    formRef.value?.resetFields();
    value.value = [];
    imageUrl.value = '';
  };
  // 获取所有标签
  const getTagList = async () => {
    const res = await getTag({ tenantId: Storage.Get('power-user').tenantid });
    tagslist.value = res.data.map(item => {
      return {
        label: item.name,
        value: item.tagId,
      };
    });
    console.log(tagslist.value);
  };
  getTagList();

  // 新增用户表单配置
  interface Tag {
    tagId: string | number; // 假设tagId可以是字符串或数字，根据实际情况调整
    name: string;
  }
  interface Department {
    value: string; // 根据实际情况，value可以是任何类型，比如string、number、object等
    isLeader: string | number; // 假设isLeader是一个布尔值
    departId?: string | number; // 假设departId可以是字符串或数字
    name?: string; // 假设name是一个字符串
    label?: string;
  }
  interface FormState {
    name: string;
    userId: string;
    tagList: Tag[];
    departList: Department[];
    mobile: string;
    passwrod: string;
    mainDepartId?: string;
    avatar: string;
  }
  const formRef = ref<FormInstance>();

  const formState = reactive<FormState>({
    name: '',
    userId: '',
    tagList: [],
    departList: [],
    mobile: '',
    passwrod: '',
    mainDepartId: '',
    avatar: '',
  });
  const onFinish = (values: any) => {
    console.log('Success:', values);
  };

  const onFinishFailed = (errorInfo: any) => {
    console.log('Failed:', errorInfo);
  };
  const tagslist = ref([] as any);
  const departmentData = ref([]);

  // 部门负责人
  const value1 = ref([] as any);
  const changeGroup = e => {
    formState.departList.forEach(item => {
      item.isLeader = value1.value.includes(item.value) ? 1 : 0;
    });
    // formState.departList.map(item => {
    //   console.log(item);

    //   return {
    //     isLeader: item.isLeader,
    //     departId: item.value,
    //     name: item.lable,
    //   };
    // });
    // console.log(formState.departList);
  };

  // 选择标签过滤出对应的标签
  const value = ref([] as any);
  const changeTags = e => {
    let filteredData = tagslist.value.filter(item => e.includes(item.value));
    formState.tagList = filteredData.map(sub => {
      return {
        tagId: sub.value,
        name: sub.label,
      };
    });
    console.log(formState.tagList);
  };

  // 选中部门处理的内容
  const changeDepart = () => {
    if (formState.departList.length == 1) {
      formState.departList.forEach(item => {
        formState.mainDepartId = item.value;
      });
    } else {
      formState.mainDepartId = '';
    }

    let found = formState.departList.some(item => item.value == formState.mainDepartId);
    if (!found) {
      formState.mainDepartId = '';
    }
    let filteredValues = value1.value.filter(value =>
      formState.departList.some(item => item.value === value),
    );
    value1.value = filteredValues;
  };

  // 查看详情
  const detailsList = ref(false);
  const detailsInfo = ref({} as any);
  const details = async record => {
    detailsList.value = true;
    title.value = '查看人员详情';
    visible.value = true;
    const res = await getUserDetail({ userId: record.userId });
    console.log(res);
    detailsInfo.value = res.data;
  };

  // 文字转拼音
  const convertToPinyin = () => {
    console.log(formState.name);

    if (title.value == '新增人员') {
      // customPinyin({
      //   曾家兴: 'zengjiaying',
      // });
      let py = pinyin(formState.name, {
        toneType: 'none',
        surname: 'head',
        // heteronym: false,
      });
      py = py
        .split(' ')
        .map(word => word.charAt(0).toUpperCase() + word.slice(1))
        .join('');
      formState.userId = py;
    }
  };
  // 头像上传

  // const beforeUpload = file => {
  //   console.log(file);
  //   return new Promise((resolve, reject) => {
  //     console.log(file);

  //     // 文件格式是否为xls,xlsx
  //     const isAcceptType = file.name.toLowerCase().substr(file.name.lastIndexOf('.'));
  //     const acceptType = '.jpg,.jpeg,.png,.JPG,.JPEG,.PNG';
  //     if (!(acceptType.indexOf(isAcceptType) > -1)) {
  //       message.warning('请上传' + acceptType + '格式文件');
  //       return reject(false);
  //     }
  //     // 文件小于10M
  //     const isLtSize = file.size / 1024 / 1024 < 10;
  //     if (!isLtSize) {
  //       message.warning('请上传10MB以内的文件');
  //       return reject(false);
  //     }
  //     return resolve(false);
  //   });
  // };
  // /**
  //  * 上传附件,没有用到附件请删除
  //  */
  const imageUrl = ref('');
  const uploadFile = async data => {
    imageUrl.value = '';
    const isAcceptType = data.file.name.toLowerCase().substr(data.file.name.lastIndexOf('.'));
    const acceptType = '.jpg,.jpeg,.png,.JPG,.JPEG,.PNG';
    if (!(acceptType.indexOf(isAcceptType) > -1)) {
      message.warning('请上传' + acceptType + '格式文件');
      return;
    }
    // 文件小于10M
    const isLtSize = data.file.size / 1024 / 1024 < 10;
    if (!isLtSize) {
      message.warning('请上传10MB以内的文件');
      return;
    }
    const res = await uploadAvatar(
      { file: data.file },
      { tenantId: Storage.Get('power-user').tenantid },
    );
    if (res.code == 0) {
      imageUrl.value = res.data.url;
    }
    console.log(res);

    // minioUpload(data.file).then(res => {
    //   console.log('res', res);
    //   if (res.code !== 0) {
    //     this.$message.error('上传图片失败');
    //   } else {
    //     this.$message.success('上传图片成功');
    //     this.infoForm.avatar = res.data.id;
    //     this.infoForm.avatarUrl = res.data.url;
    //   }
    // });
  };
  const setMange =(record)=>{
    saveMange({userId:record.userId}).then(res=>{
      if(res.code==0){
        message.success('设置成功')
        record.isOwner = true;
      }
    })
  }
  const removeMange =(record)=>{

    deleteMange({userId:record.userId}).then(res=>{
      if(res.code==0){
        message.success('撤销成功')
        record.isOwner = false;
      }
    })
  }
</script>
<style scoped lang="scss">
  .box {
    .avatar {
      display: flex;
      align-items: center;
      // justify-content: center;
      margin-left: 30px;
      img {
        width: 50px;
        border-radius: 50%;
      }
      a {
        margin-left: 10px;
      }
    }
    .operate {
      color: #2196f8;
    }
    .btn {
      // float: right;
      // padding-bottom: 20px;
      margin: 20px 0;
    }
    .search {
      display: flex;
      justify-content: space-between;
      // width: 250px;
      // float: left;
      ::v-deep .ant-input-affix-wrapper {
        width: 300px;
      }
      .query {
        // .
        ::v-deep .ant-btn {
          margin-right: 20px;
        }
      }
      .name {
        display: flex;
        align-items: center;
      }
    }
    // :global(.ant-modal-body) {
    //   .depart > span {
    //     font-size: 18px;
    //     // color: #1890ff !important; //
    //   }
    //   // background: yellow;
    // }
    .globalModal {
    }
  }
  // ::v-deep .ant-modal {
  // 自定义样式
  // form表单样式
  .projectItem {
    padding-left: 0px;
    padding-right: 20px;

    ::v-deep .ant-col {
      width: auto;
      height: auto;
    }
  }
  // }
</style>
